package interfaces;

import com.example.money.R;

import databases.DsConta;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ContaAddActivity extends Activity {
	private String curNome; 
	private Bundle extras;
	private DsConta dbDataSource;
	private EditText editTextNome;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_conta_add);
		addListenersOnButtons();
		
		curNome = "";
		
		extras = getIntent().getExtras();
		
		dbDataSource = new DsConta(this);
		dbDataSource.open();
		
		editTextNome = (EditText)findViewById(R.id.tvw_conta_nome);
		
		if(extras != null)
		{
			curNome = extras.getString("nome");
			editTextNome.setText(curNome);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_contas, menu);
		return true;
	}

	public void addListenersOnButtons() {
		Button btnCancelar = (Button)findViewById(R.id.button_cancelar);
		btnCancelar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		Button btnSalvar = (Button) findViewById(R.id.btn_conta_salvar);
		btnSalvar.setOnClickListener(new OnClickListener(){
			
			public void onClick(View v) {
				String nome = editTextNome.getText().toString();
 				
 				if(nome.length() == 0)
 				{
 					Toast.makeText(getApplicationContext(), R.string.nome_obrigatorio, Toast.LENGTH_LONG).show();
 				}
 				else
 				{
 					if(nome.equals(curNome))
 					{
 						finish();
 					}
 					else if(dbDataSource.hasName(nome))
					{
						Toast.makeText(getApplicationContext(), R.string.nome_usado, Toast.LENGTH_LONG).show();
					}
					else
					{
						if(extras == null)
						{
							if(dbDataSource.add(nome) == null)
							{
								Toast.makeText(getApplicationContext(), R.string.conta_salvar_erro, Toast.LENGTH_LONG).show();
							}
							else
							{
								Toast.makeText(getApplicationContext(), R.string.conta_salvar_sucesso, Toast.LENGTH_LONG).show();
								editTextNome.setText("");
								
								finish();
							}
						}
						else
						{
							if(dbDataSource.rename(extras.getLong("id"), nome))
							{
								Toast.makeText(getApplicationContext(), R.string.conta_renomear_sucesso, Toast.LENGTH_LONG).show();
								editTextNome.setText("");
								
								finish();							
							}
							else
							{
								Toast.makeText(getApplicationContext(), R.string.conta_renomear_erro, Toast.LENGTH_LONG).show();
							}
						}
					}
 				}
				
			}
			
			
		});

	}
}
